package edu.sju.ssm.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
// @MapperScan({"edu.sju.ssm.mapper"})
public class MyBatisConfig {
    private String mappersBasePackage = "edu.sju.ssm.mapper";

    // @Value("classpath:mybatis-config.xml")
    // private Resource mybatisConfig;

    @Bean
	public SqlSessionFactory sqlSessionFactory(@Value("#{dataSource}") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        // factory.setConfiguration(configuration());
        // factory.setConfigLocation(mybatisConfig);
        return factory.getObject();
    }
    
    // It works only when a configuration exists and a mapperInterface has been set
    // @Bean
    // @Autowired
    // public PublisherMapper publisherMapper(SqlSessionFactory sqlSessionFactory) throws Exception {
    //     MapperFactoryBean<PublisherMapper> mapperFactory = new MapperFactoryBean<>();
    //     mapperFactory.setSqlSessionFactory(sqlSessionFactory);
    //     mapperFactory.setMapperInterface(PublisherMapper.class);
    //     return mapperFactory.getObject();
    // }

    // or alternatively, put a @MapperScan on the class, which makes no difference
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage(mappersBasePackage);
        return configurer;
    }

    // private org.apache.ibatis.session.Configuration configuration() {
    //     org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
    //     configuration.getTypeAliasRegistry().registerAlias(Publisher.class);
    //     configuration.addMapper(PublisherMapper.class);
    //     return configuration;
    // }
}
